<template>
  <el-drawer v-model="dialogStatus" :close-on-click-modal="false" size="50%"
             @close="dialogOfClosedMethods(false)">
    <template #header>
      <h4>{{ title }}</h4>
    </template>
    <template #default>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" inline-message>
        <el-tabs
            v-model="activeName"
            type="card"
            class="demo-tabs"
        >
          <el-tab-pane label="基本信息" name="first">

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户类型" prop="customerType">
                  <el-select v-model="form.customerType" placeholder="请选择">
                    <el-option label="个人" value="个人"/>
                    <el-option label="企业" value="企业"/>
                  </el-select>
                </el-form-item>
              </el-col>
              
              <!-- 生成全部信息按钮 -->
              <el-col :span="12">
                <el-form-item>
                  <el-button type="success" @click="generateAllCustomerInfo">
                    生成全部信息
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 个人客户身份证信息 -->
            <div v-if="form.customerType === '个人'">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-row :gutter="10">
                    <!-- 身份证人像照 -->
                    <el-col :span="8">
                      <div class="id-card-upload-container">
                        <el-upload
                          class="id-card-uploader"
                          action="#"
                          :auto-upload="false"
                          :show-file-list="false"
                          :on-change="(file) => handleIdCardChange(file, 'portrait')"
                        >
                          <img v-if="idCardImages.portrait" :src="idCardImages.portrait" class="id-card-image" @click.stop="handlePictureCardPreview('portrait')"/>
                          <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                        <div class="image-actions" v-if="idCardImages.portrait">
                          <el-button 
                            type="danger" 
                            icon="Delete" 
                            circle 
                            size="small" 
                            @click="handleRemoveImage('portrait')"
                          />
                        </div>
                        <div class="image-label">身份证人像照</div>
                        <el-button size="small" type="primary" @click="() => performOCR('portrait')" :disabled="!idCardImages.portrait">
                          OCR识别
                        </el-button>
                      </div>
                    </el-col>
                    
                    <!-- 身份证国徽照 -->
                    <el-col :span="8">
                      <div class="id-card-upload-container">
                        <el-upload
                          class="id-card-uploader"
                          action="#"
                          :auto-upload="false"
                          :show-file-list="false"
                          :on-change="(file) => handleIdCardChange(file, 'nationalEmblem')"
                        >
                          <img v-if="idCardImages.nationalEmblem" :src="idCardImages.nationalEmblem" class="id-card-image" @click.stop="handlePictureCardPreview('nationalEmblem')"/>
                          <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                        <div class="image-actions" v-if="idCardImages.nationalEmblem">
                          <el-button 
                            type="danger" 
                            icon="Delete" 
                            circle 
                            size="small" 
                            @click="handleRemoveImage('nationalEmblem')"
                          />
                        </div>
                        <div class="image-label">身份证国徽照</div>
                        <el-button size="small" type="primary" @click="() => performOCR('nationalEmblem')" :disabled="!idCardImages.nationalEmblem">
                          OCR识别
                        </el-button>
                      </div>
                    </el-col>
                    
                    <!-- 人脸识别照片 -->
                    <el-col :span="8">
                      <div class="id-card-upload-container">
                        <el-upload
                          class="id-card-uploader"
                          action="#"
                          :auto-upload="false"
                          :show-file-list="false"
                          :on-change="(file) => handleIdCardChange(file, 'face')"
                        >
                          <img v-if="idCardImages.face" :src="idCardImages.face" class="id-card-image" @click.stop="handlePictureCardPreview('face')"/>
                          <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                        <div class="image-actions" v-if="idCardImages.face">
                          <el-button 
                            type="danger" 
                            icon="Delete" 
                            circle 
                            size="small" 
                            @click="handleRemoveImage('face')"
                          />
                        </div>
                        <div class="image-label">人脸识别照片</div>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
                
                <!-- 右侧：身份证信息展示 -->
                <el-col :span="14">
                  <div class="id-card-info-container">
                    <div class="id-card-info-title">身份证信息</div>
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="姓名">
                          <el-input v-model="idCardInfo.name" readonly/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="性别">
                          <el-input v-model="idCardInfo.gender" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="民族">
                          <el-input v-model="idCardInfo.nation" readonly/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="出生">
                          <el-input v-model="idCardInfo.birthday" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="户籍地址">
                          <el-input v-model="idCardInfo.address" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="公民身份证号">
                          <el-input v-model="idCardInfo.idCertNo" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="签发机关">
                          <el-input v-model="idCardInfo.issueAuthority" readonly/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="有效期限">
                          <el-input v-model="idCardInfo.validDate" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
              
              <!-- 添加间距 -->
              <div class="form-spacing"></div>
            </div>
            
            <!-- 企业客户营业执照信息 -->
            <div v-else-if="form.customerType === '企业'">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-row :gutter="10">
                    <!-- 营业执照 -->
                    <el-col :span="24">
                      <div class="id-card-upload-container">
                        <el-upload
                          class="id-card-uploader"
                          action="#"
                          :auto-upload="false"
                          :show-file-list="false"
                          :on-change="(file) => handleIdCardChange(file, 'businessLicense')"
                        >
                          <img v-if="idCardImages.businessLicense" :src="idCardImages.businessLicense" class="id-card-image business-license-image" @click.stop="handlePictureCardPreview('businessLicense')"/>
                          <el-icon v-else class="id-card-uploader-icon business-license-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                        <div class="image-actions" v-if="idCardImages.businessLicense">
                          <el-button 
                            type="danger" 
                            icon="Delete" 
                            circle 
                            size="small" 
                            @click="handleRemoveImage('businessLicense')"
                          />
                        </div>
                        <div class="image-label">营业执照</div>
                        <el-button size="small" type="primary" @click="() => performOCR('businessLicense')" :disabled="!idCardImages.businessLicense">
                          OCR识别
                        </el-button>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
                
                <!-- 右侧：营业执照信息展示 -->
                <el-col :span="14">
                  <div class="id-card-info-container">
                    <div class="id-card-info-title">营业执照信息</div>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="企业名称">
                          <el-input v-model="businessLicenseInfo.companyName" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="统一社会信用代码">
                          <el-input v-model="businessLicenseInfo.creditCode" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="法人">
                          <el-input v-model="businessLicenseInfo.legalPerson" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="注册资本">
                          <el-input v-model="businessLicenseInfo.regCapital" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="成立日期">
                          <el-input v-model="businessLicenseInfo.establishDate" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="营业期限">
                          <el-input v-model="businessLicenseInfo.validPeriod" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span="24">
                        <el-form-item label="住所">
                          <el-input v-model="businessLicenseInfo.address" readonly/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
              
              <!-- 添加间距 -->
              <div class="form-spacing"></div>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="form.customerName"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户分组">
                  <el-select v-model="form.segmentId" clearable placeholder="请选择">
                    <el-option v-for="(item, index) in dataSegmentList" :key="index"
                               :value="item.id" :label="item.segmentName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属行业" prop="industry">
                  <el-input v-model="form.industry"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所在地区">
                  <el-cascader
                      v-model="region"
                      :options="pcTextArr"
                      :props="{ emitPath: true, checkStrictly: true }"
                      clearable
                      filterable
                      placeholder="请选择省市"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="居住地址" prop="address">
                  <el-input v-model="form.address"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="来源渠道">
                  <el-select v-model="form.customerFrom" clearable placeholder="请选择">
                    <el-option
                      v-for="item in channelOptions"
                      :key="item.channelCode"
                      :label="item.channelName"
                      :value="item.channelCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来源商户">
                  <el-select v-model="form.merchantCode" clearable placeholder="请选择">
                    <el-option
                      v-for="item in merchantOptions"
                      :key="item.id"
                      :label="item.merchantName"
                      :value="item.merchantCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input v-model="form.email"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="customerHead">
                  <el-input v-model="form.customerHead"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 个人客户信息字段 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="婚姻类型">
                  <el-select v-model="form.maritalStatus" clearable placeholder="请选择婚姻类型">
                    <el-option label="未婚" value="1"></el-option>
                    <el-option label="已婚" value="2"></el-option>
                    <el-option label="离异" value="3"></el-option>
                    <el-option label="丧偶" value="4"></el-option>
                    <el-option label="未知" value="6"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="教育程度">
                  <el-select v-model="form.education" clearable placeholder="请选择教育程度">
                    <el-option label="小学" value="小学"></el-option>
                    <el-option label="初中" value="初中"></el-option>
                    <el-option label="高中" value="高中"></el-option>
                    <el-option label="大专" value="大专"></el-option>
                    <el-option label="本科" value="本科"></el-option>
                    <el-option label="硕士" value="硕士"></el-option>
                    <el-option label="博士" value="博士"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="住房类型">
                  <el-select v-model="form.housingType" clearable placeholder="请选择住房类型">
                    <el-option label="自有住房" value="自有住房"></el-option>
                    <el-option label="租赁住房" value="租赁住房"></el-option>
                    <el-option label="公司宿舍" value="公司宿舍"></el-option>
                    <el-option label="亲属住房" value="亲属住房"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收入类型">
                  <el-select v-model="form.incomeType" clearable placeholder="请选择收入类型">
                    <el-option label="工资收入" value="工资收入"></el-option>
                    <el-option label="经营收入" value="经营收入"></el-option>
                    <el-option label="投资收入" value="投资收入"></el-option>
                    <el-option label="其他收入" value="其他收入"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 添加工作相关信息字段 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="公司名称">
                  <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公司电话">
                  <el-input v-model="form.companyTel" placeholder="请输入公司电话"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="公司所在地区">
                  <el-cascader
                      v-model="companyRegion"
                      :options="pcTextArr"
                      :props="{ emitPath: true, checkStrictly: true }"
                      clearable
                      filterable
                      placeholder="请选择省市"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公司详细地址">
                  <el-input v-model="form.companyAddress" placeholder="请输入公司详细地址"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="公司性质">
                  <el-select v-model="form.companyNature" clearable placeholder="请选择公司性质">
                    <el-option label="外商投资企业" value="301"></el-option>
                    <el-option label="个体工商户" value="302"></el-option>
                    <el-option label="政府机关" value="303"></el-option>
                    <el-option label="私营" value="304"></el-option>
                    <el-option label="国企" value="305"></el-option>
                    <el-option label="合资" value="306"></el-option>
                    <el-option label="民营" value="307"></el-option>
                    <el-option label="事业单位" value="308"></el-option>
                    <el-option label="有限责任公司" value="309"></el-option>
                    <el-option label="股份责任公司" value="310"></el-option>
                    <el-option label="独资企业" value="311"></el-option>
                    <el-option label="合伙制企业" value="312"></el-option>
                    <el-option label="其他" value="300"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公司行业">
                  <el-select v-model="form.companyIndustry" clearable placeholder="请选择公司行业">
                    <el-option label="农、林、牧、渔业" value="1"></el-option>
                    <el-option label="采矿业" value="2"></el-option>
                    <el-option label="制造业" value="3"></el-option>
                    <el-option label="电力、燃气及水的生产和供应业" value="4"></el-option>
                    <el-option label="建筑业" value="5"></el-option>
                    <el-option label="交通运输、仓储和邮政业" value="6"></el-option>
                    <el-option label="信息传输、计算机服务和软件业" value="7"></el-option>
                    <el-option label="批发和零售业" value="8"></el-option>
                    <el-option label="住宿和餐饮业" value="9"></el-option>
                    <el-option label="金融业" value="10"></el-option>
                    <el-option label="房地产业" value="11"></el-option>
                    <el-option label="租赁和商务服务业" value="12"></el-option>
                    <el-option label="科学研究、技术服务业和地质勘察业" value="13"></el-option>
                    <el-option label="水利、环境和公共设施管理业" value="14"></el-option>
                    <el-option label="居民服务和其他服务业" value="15"></el-option>
                    <el-option label="教育" value="16"></el-option>
                    <el-option label="卫生和社会工作" value="17"></el-option>
                    <el-option label="文化、体育和娱乐业" value="18"></el-option>
                    <el-option label="公共管理、社会保障和社会组织" value="19"></el-option>
                    <el-option label="国际组织" value="20"></el-option>
                    <el-option label="学生" value="21"></el-option>
                    <el-option label="其他" value="22"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="备注">
              <el-input v-model="form.content" type="textarea"/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="开票信息" name="second">
            <el-row :gutter="20">
              <el-col :span="span">
                <el-form-item label="纳税人识别号" prop="taxNumber">
                  <el-input v-model="form.taxNumber"/>
                </el-form-item>
              </el-col>
              <el-col :span="span">
                <el-form-item label="账户名称" prop="taxBankAccount">
                  <el-input v-model="form.taxBankAccount"/>
                </el-form-item>
              </el-col>
              <el-col :span="span">
                <el-form-item label="开户银行" prop="taxBank">
                  <el-input v-model="form.taxBank"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="span">
                <el-form-item label="银行账户" prop="taxBankAccountNumber">
                  <el-input v-model="form.taxBankAccountNumber"/>
                </el-form-item>
              </el-col>
              <el-col :span="span">
                <el-form-item label="联系方式" prop="taxContact">
                  <el-input v-model="form.taxContact"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogOfClosedMethods(false)">{{ t('org.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t('org.confirm') }}</el-button>
      </div>
    </template>
  </el-drawer>
  
  <!-- 图片预览对话框 -->
  <el-image-viewer
    v-if="previewVisible"
    :url-list="[previewImageUrl]"
    @close="previewVisible = false"
  />
</template>

<script setup lang="ts">
import {ElForm} from 'element-plus'
import {reactive, ref, toRefs, watch} from 'vue'
import {useI18n} from 'vue-i18n'
import modal from '@/plugins/modal'
import {getCustomerOne, saveCustomer, updateCustomer} from '@/api/customer/customer'
import {listCustomerSegment} from '@/api/customer/customer-segment'
import {listMerchant} from '@/api/merchant/merchant'
import {listChannel} from '@/api/channel/channel'
import { ElImageViewer } from 'element-plus'
import request from '@/utils/request'

const region = ref<string[]>([]) // 用于省市联动选择
const companyRegion = ref<string[]>([]) // 用于公司省市联动选择
import {pcTextArr} from 'element-china-area-data'
import { Plus } from '@element-plus/icons-vue'

const activeName = ref('first')
const emit = defineEmits(['dialogOfClosedMethods'])
const dialogStatus = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const {t} = useI18n()

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref('')

interface FormModel {
  id?: string
  customerName: string
  customerType: string
  segmentId: string
  industry: string
  province?: string
  city?: string
  address: string
  email: string
  phone: string
  website: string
  content?: string
  taxNumber: string
  taxContact: string
  taxBank: string
  taxBankAccount: string
  taxBankAccountNumber: string
  customerHead: string
  customerFrom?: string
  merchantCode?: string
  referrer: string
  // 身份证相关信息
  idCardName?: string
  idCardNumber?: string
  idCardGender?: string
  idCardBirth?: string
  idCardAddress?: string
  // 图片URL
  idCardFrontImage?: string
  idCardBackImage?: string
  businessLicenseImage?: string
  facePhotoImage?: string
}

interface FormState {
  form: FormModel
  rules: Record<string, any>
}

const props = defineProps<{
  title?: string
  open?: boolean
  formId?: string
}>()

interface SegmentModel {
  id?: string
  segmentName: string
}

// 商户选项数据
const merchantOptions = ref([])

// 渠道选项数据
const channelOptions = ref([])

// 身份证图片对象
const idCardImages = ref({
  nationalEmblem: '', // 国徽面
  portrait: '',       // 人像面
  face: '',           // 人脸识别
  businessLicense: '' // 营业执照
})

// 身份证信息
const idCardInfo = ref({
  name: '',
  gender: '',
  nation: '',
  birthday: '',
  address: '',
  idCertNo: '',
  issueAuthority: '',
  validDate: ''
})

// 营业执照信息
const businessLicenseInfo = ref({
  companyName: '',    // 企业名称
  creditCode: '',     // 统一社会信用代码
  legalPerson: '',    // 法人
  regCapital: '',     // 注册资本
  establishDate: '',  // 成立日期
  validPeriod: '',    // 营业期限
  address: ''         // 住所
})

const data = reactive<FormState>({
  form: {
    customerName: '',
    customerType: '',
    segmentId: '',
    industry: '',
    address: '',
    email: '',
    phone: '',
    website: '',
    customerHead: '',
    customerFrom: '',
    merchantCode: '',
    referrer: '',
    taxNumber: '',
    taxContact: '',
    taxBank: '',
    taxBankAccount: '',
    taxBankAccountNumber: '',
    // 身份证相关信息
    idCardName: '',
    idCardNumber: '',
    idCardGender: '',
    idCardBirth: '',
    idCardAddress: '',
    // 图片URL
    idCardFrontImage: '',
    idCardBackImage: '',
    businessLicenseImage: '',
    facePhotoImage: ''
  },
  rules: {
    customerType: [
      {required: true, message: "客户类型不能为空", trigger: 'blur'}
    ],
    phone: [
      {required: true, message: "联系电话不能为空", trigger: 'blur'}
    ]
  }
})

const {form, rules} = toRefs(data)
const dataSegmentList = ref<Array<SegmentModel>>([])
const span = ref(24)

watch(
    () => props.open,
    (val) => {
      if (val) {
        dialogStatus.value = val
        getSegmentList()
        getMerchantList()
        getChannelList()
        if (props.formId) {
          getCustomerOne(props.formId).then((res: any) => {
            form.value = res.data
            const regionArr: any[] = [];
            if (res.data.province) {
              regionArr.push(res.data.province);
              if (res.data.city) {
                regionArr.push(res.data.city);
              }
            }
            region.value = regionArr;
            
            // 设置公司地区字段
            const companyRegionArr: any[] = [];
            if (res.data.companyProvince) {
              companyRegionArr.push(res.data.companyProvince);
              if (res.data.companyCity) {
                companyRegionArr.push(res.data.companyCity);
              }
            }
            companyRegion.value = companyRegionArr;
          })
        } else {
          reset()
        }
      } else {
        reset()
      }
    },
    {immediate: true}
)

watch(region, (val) => {
  data.form.province = val[0] || ''
  data.form.city = val[1] || ''
})

watch(companyRegion, (val) => {
  data.form.companyProvince = val[0] || ''
  data.form.companyCity = val[1] || ''
})

function dialogOfClosedMethods(val: any) {
  dialogStatus.value = false
  emit('dialogOfClosedMethods', val)
}

function reset() {
  form.value = {
    customerName: '',
    segmentId: '',
    customerType: '',
    industry: '',
    address: '',
    email: '',
    phone: '',
    website: '',
    customerHead: '',
    customerFrom: '',
    merchantCode: '',
    referrer: '',
    taxNumber: '',
    taxContact: '',
    taxBank: '',
    taxBankAccount: '',
    taxBankAccountNumber: '',
    identifier: '',
    // 重置工作相关信息字段
    companyName: '',
    companyProvince: '',
    companyCity: '',
    companyAddress: '',
    companyTel: '',
    companyNature: '',
    companyIndustry: '',
    // 重置个人客户信息字段
    maritalStatus: '',
    education: '',
    housingType: '',
    incomeType: ''
  }
  // 重置身份证图片
  idCardImages.value = {
    nationalEmblem: '',
    portrait: '',
    face: '',
    businessLicense: ''
  }
  // 重置身份证信息
  idCardInfo.value = {
    name: '',
    gender: '',
    nation: '',
    birthday: '',
    address: '',
    idCertNo: '',
    issueAuthority: '',
    validDate: ''
  }
  // 重置营业执照信息
  businessLicenseInfo.value = {
    companyName: '',
    creditCode: '',
    legalPerson: '',
    regCapital: '',
    establishDate: '',
    validPeriod: '',
    address: ''
  }
  formRef?.value?.resetFields()
  region.value = []
  companyRegion.value = []
}

function getSegmentList() {
  listCustomerSegment({
    pageNumber: 1,
    pageSize: 10000,
  }).then((response: any) => {
    dataSegmentList.value = response.data.records
  })
}

// 获取商户列表
function getMerchantList() {
  listMerchant({}).then((res: any) => {
    merchantOptions.value = res.data.records || res.data
  }).catch(() => {
    // 使用默认数据
    merchantOptions.value = [
      {id: "1", merchantName: "自平台", merchantCode: "SELF"},
      {id: "2", merchantName: "示例商户2", merchantCode: "MERCHANT_2"}
    ]
  })
}

// 获取渠道列表
function getChannelList() {
  listChannel({}).then((res: any) => {
    channelOptions.value = res.data.records || res.data
  }).catch(() => {
    // 使用默认数据
    channelOptions.value = [
      {channelCode: "CHANNEL_1", channelName: "渠道1"},
      {channelCode: "CHANNEL_2", channelName: "渠道2"}
    ]
  })
}

// 上传文件的封装方法
function uploadImage(data: any): Promise<any> {
  return request({
    url: '/ossstorage/upload',
    method: 'post',
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// 处理身份证图片上传
const handleIdCardChange = (file: any, type: string) => {
  // 检查文件是否存在
  if (!file || !file.raw) {
    modal.msgError('请选择有效的文件');
    return;
  }
  
  // 构建表单数据
  const formData = new FormData();
  formData.append('file', file.raw);
  
  // 使用封装的上传方法
  uploadImage(formData).then((result: any) => {
    if (result.code === "0") {
      // 上传成功，保存图片URL
      if (type === 'portrait') {
        idCardImages.value.portrait = result.data.url;
        // 同时保存到表单中
        form.value.idCardFrontImage = result.data.url;
      } else if (type === 'nationalEmblem') {
        idCardImages.value.nationalEmblem = result.data.url;
        // 同时保存到表单中
        form.value.idCardBackImage = result.data.url;
      } else if (type === 'face') {
        idCardImages.value.face = result.data.url;
        // 同时保存到表单中
        form.value.facePhotoImage = result.data.url;
      }
    } else {
      modal.msgError('上传失败: ' + result.message);
    }
  }).catch((error: any) => {
    modal.msgError('上传出错: ' + error.message);
  });
};

// 处理营业执照图片上传
const handleBusinessLicenseChange = (file: any) => {
  // 检查文件是否存在
  if (!file || !file.raw) {
    modal.msgError('请选择有效的文件');
    return;
  }
  
  // 构建表单数据
  const formData = new FormData();
  formData.append('file', file.raw);
  
  // 使用封装的上传方法
  uploadImage(formData).then((result: any) => {
    if (result.code === "0") {
      // 上传成功，保存图片URL
      idCardImages.value.businessLicense = result.data.url;
      // 同时保存到表单中
      form.value.businessLicenseImage = result.data.url;
    } else {
      modal.msgError('上传失败: ' + result.message);
    }
  }).catch((error: any) => {
    modal.msgError('上传出错: ' + error.message);
  });
};

// 处理图片预览
const handlePictureCardPreview = (type: string) => {
  previewImageUrl.value = idCardImages.value[type]
  previewVisible.value = true
}

// 处理图片删除
const handleRemoveImage = (type: string) => {
  idCardImages.value[type] = ''
}

// 执行OCR识别（mock实现）
const performOCR = (type: string) => {
  modal.loading('正在识别中，请稍候...')
  
  // 模拟延迟
  setTimeout(() => {
    modal.closeLoading()
    
    if (type === 'portrait') {
      // 模拟身份证人像面识别结果
      idCardInfo.value.name = '张三'
      idCardInfo.value.gender = '男'
      idCardInfo.value.nation = '汉'
      idCardInfo.value.birthday = '1990年1月1日'
      idCardInfo.value.address = '北京市朝阳区某某街道123号'
      idCardInfo.value.idCertNo = '110101199001011234' // 公民身份证号由人像面识别
      form.value.customerName = '张三'
      form.value.identifier = '110101199001011234'
      modal.msgSuccess('OCR识别完成，已填充客户名称和身份证信息')
    } else if (type === 'nationalEmblem') {
      // 模拟身份证国徽面识别结果
      idCardInfo.value.issueAuthority = '北京市公安局朝阳分局'
      idCardInfo.value.validDate = '2020.01.01-2030.01.01'
      modal.msgSuccess('OCR识别完成，已填充签发机关和有效期限')
    } else if (type === 'businessLicense') {
      // 模拟营业执照识别结果
      businessLicenseInfo.value.companyName = '某某科技有限公司'
      businessLicenseInfo.value.creditCode = '912345678901234567'
      businessLicenseInfo.value.legalPerson = '张三'
      businessLicenseInfo.value.regCapital = '1000万元'
      businessLicenseInfo.value.establishDate = '2020-01-01'
      businessLicenseInfo.value.validPeriod = '2020-01-01 至 长期'
      businessLicenseInfo.value.address = '北京市朝阳区某某街道123号'
      
      // 填充到表单中
      form.value.customerName = businessLicenseInfo.value.companyName
      form.value.identifier = businessLicenseInfo.value.creditCode
      modal.msgSuccess('OCR识别完成，已填充企业信息')
    }
  }, 1500)
}

function submitForm() {
  const handleResponse = (res: any, successMessage: string) => {
    if (res.code === "0") {
      modal.msgSuccess(successMessage)
      dialogOfClosedMethods(true)
    } else {
      modal.msgError(res.message)
    }
  }

  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 处理省市数据
      if (region.value && region.value.length > 0) {
        form.value.province = region.value[0]
        form.value.city = region.value.length > 1 ? region.value[1] : ''
      }
      
      // 映射身份证和营业执照图片URL到表单对象中
      form.value.idCardFrontImage = idCardImages.value.portrait;
      form.value.idCardBackImage = idCardImages.value.nationalEmblem;
      form.value.businessLicenseImage = idCardImages.value.businessLicense;
      form.value.faceImage = idCardImages.value.face;
      
      // 映射身份证信息到表单对象中
      form.value.idCardName = idCardInfo.value.name;
      form.value.idCardGender = idCardInfo.value.gender;
      form.value.idCardNation = idCardInfo.value.nation;
      form.value.idCardAddress = idCardInfo.value.address;
      form.value.idCardIssueAuthority = idCardInfo.value.issueAuthority;
      
      // 映射营业执照信息到表单对象中
      form.value.businessLicenseName = businessLicenseInfo.value.companyName;
      form.value.businessLicenseCreditCode = businessLicenseInfo.value.creditCode;
      form.value.businessLicenseLegalPerson = businessLicenseInfo.value.legalPerson;
      form.value.businessLicenseRegCapital = businessLicenseInfo.value.regCapital;
      form.value.businessLicenseAddress = businessLicenseInfo.value.address;

      if (form.value.id) {
        updateCustomer(form.value).then((res: any) => {
          handleResponse(res, t('jbx.alert.update.success'))
        })
      } else {
        saveCustomer(form.value).then((res: any) => {
          handleResponse(res, t('jbx.alert.add.success'))
        })
      }
    }
  })
}

function generateAllCustomerInfo() {
  // 随机生成数据的辅助函数
  const randomItem = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)];
  const randomString = (len: number) => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < len; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  };
  
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
  const genders = ['男', '女'];
  const nations = ['汉', '满', '蒙', '回', '藏', '维吾尔', '苗', '彝'];
  const addresses = ['北京市朝阳区某某街道123号', '上海市浦东新区某某路456号', '广州市天河区某某大道789号', '深圳市南山区某某街道101号'];
  const industries = ['制造业', '信息技术', '金融', '教育', '医疗', '零售', '餐饮', '房地产'];
  const companyNames = ['某某科技有限公司', '某某贸易有限公司', '某某投资有限公司', '某某咨询有限公司'];
  const capitals = ['100万元', '500万元', '1000万元', '2000万元'];
  const phones = ['13800138000', '13900139000', '13700137000', '13600136000'];
  const emails = ['example@email.com', 'test@example.com', 'info@company.com', 'contact@business.com'];
  const customerTypes = ['个人', '企业'];
  const maritalStatuses = ['1', '2', '3', '4', '6'];
  const educations = ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '其他'];
  const housingTypes = ['自有住房', '租赁住房', '公司宿舍', '亲属住房', '其他'];
  const incomeTypes = ['工资收入', '经营收入', '投资收入', '其他收入'];
  const companyNatures = ['国有', '私营', '合资', '外商独资', '股份制'];
  
  // 根据当前客户类型生成信息
  const customerType = form.value.customerType || randomItem(customerTypes);
  
  if (customerType === '个人') {
    // 生成身份证信息
    const name = randomItem(names);
    idCardInfo.value.name = name;
    form.value.customerName = name;
    idCardInfo.value.gender = randomItem(genders);
    idCardInfo.value.nation = randomItem(nations);
    idCardInfo.value.birthday = '1990年1月1日';
    const address = randomItem(addresses);
    idCardInfo.value.address = address;
    const idCertNo = '11010119900101' + Math.floor(Math.random() * 10000);
    idCardInfo.value.idCertNo = idCertNo;
    form.value.identifier = idCertNo;
    idCardInfo.value.issueAuthority = '北京市公安局朝阳分局';
    idCardInfo.value.validDate = '2020.01.01-2030.01.01';
  } else {
    // 生成营业执照信息
    const companyName = randomItem(companyNames);
    businessLicenseInfo.value.companyName = companyName;
    form.value.customerName = companyName;
    const creditCode = '91234567890123' + Math.floor(Math.random() * 100);
    businessLicenseInfo.value.creditCode = creditCode;
    form.value.identifier = creditCode;
    businessLicenseInfo.value.legalPerson = randomItem(names);
    businessLicenseInfo.value.regCapital = randomItem(capitals);
    businessLicenseInfo.value.establishDate = '2020-01-01';
    businessLicenseInfo.value.validPeriod = '2020-01-01 至 长期';
    businessLicenseInfo.value.address = randomItem(addresses);
  }
  
  // 生成其他信息
  form.value.segmentId = '';
  form.value.industry = randomItem(industries);
  form.value.address = randomItem(addresses);
  form.value.email = randomItem(emails);
  form.value.phone = randomItem(phones);
  form.value.website = 'www.' + randomString(8) + '.com';
  form.value.customerHead = randomItem(names);
  form.value.customerFrom = 'CHANNEL_1';
  form.value.merchantCode = 'SELF';
  form.value.referrer = randomItem(names);
  form.value.taxNumber = '12345678901234567' + Math.floor(Math.random() * 10);
  form.value.taxContact = randomItem(phones);
  form.value.taxBank = '中国工商银行';
  form.value.taxBankAccount = randomItem(names) + '公司';
  form.value.taxBankAccountNumber = '12345678901234567' + Math.floor(Math.random() * 10);
  form.value.content = '备注信息' + randomString(10);
  
  // 生成工作相关信息字段
  form.value.companyName = randomItem(companyNames);
  form.value.companyProvince = '北京市';
  form.value.companyCity = '朝阳区';
  form.value.companyAddress = randomItem(addresses);
  form.value.companyTel = randomItem(phones);
  form.value.companyNature = randomItem(companyNatures);
  form.value.companyIndustry = randomItem(industries);
  
  // 生成个人客户信息字段
  form.value.maritalStatus = randomItem(maritalStatuses);
  form.value.education = randomItem(educations);
  form.value.housingType = randomItem(housingTypes);
  form.value.incomeType = randomItem(incomeTypes);
  
  modal.msgSuccess('已随机生成全部信息');
}

</script>

<style scoped>
.id-card-upload-container {
  text-align: center;
  margin-bottom: 15px;
  position: relative;
}

.id-card-uploader {
  display: inline-block;
  position: relative;
}

.id-card-uploader .id-card-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 100px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.id-card-uploader .id-card-image {
  width: 100px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  position: relative;
}

/* 营业执照图片样式 */
.id-card-uploader .business-license-image {
  width: 220px;
  height: 140px;
}

.id-card-uploader .business-license-uploader-icon {
  width: 220px;
  height: 140px;
  line-height: 140px;
}

.id-card-uploader:hover .id-card-uploader-icon {
  border-color: #409eff;
}

.image-label {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.image-actions {
  position: absolute;
  top: -8px;
  right: -8px;
  display: flex;
  gap: 5px;
  z-index: 10;
}

/* 特别针对营业执照图片的删除按钮定位 */
.business-license-uploader-icon + .image-actions,
.business-license-image + .image-actions {
  right: -5px;
}

.id-card-info-container {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 12px;
  min-height: 260px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.id-card-info-title {
  font-weight: bold;
  margin-bottom: 12px;
  text-align: center;
  color: #303133;
}

.id-card-info-container :deep(.el-form-item__label) {
  font-size: 12px;
  padding: 0 5px 0 0;
}

.id-card-info-container :deep(.el-form-item) {
  margin-bottom: 8px;
}

.id-card-info-container :deep(.el-form-item__content) {
  font-size: 12px;
}

/* 添加身份证信息区域与下面表单项之间的间距 */
.form-spacing {
  height: 20px;
}
</style>